//
//  CJExten+SDWebImage.swift
//  CJPack
//
//  Created by 陈警卫 on 2023/1/31.
//

import UIKit
import Foundation
import SDWebImage
import SnapKit

/// 基类占位图
open class CJExtenImageHolder: UIView {
    open var cj_data: AnyObject?
}

/// 默认占位图
open class CJExtenImageHolderView: CJExtenImageHolder {
    
    open override var cj_data: AnyObject? {
        didSet {
            cj_setHolderImage()
        }
    }
    
    open func cj_setHolderImage() {
        if let cj_data = cj_data {
            if cj_data.isKind(of: UIImage.self) {
                cj_holderImageView.image = cj_data as? UIImage
            }
        }
    }
    
    open var cj_holderImageView: UIImageView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.cj_color("E5E5E5")
        cj_holderImageView = UIImageView()
        cj_holderImageView.contentMode = .scaleAspectFit
        addSubview(cj_holderImageView)
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        let w = cj_width * 0.6
        let h = cj_height * 0.6
        let v = min(w, h)
        cj_holderImageView.frame = CGRect(x: 0, y: 0, width: v, height: v)
        cj_holderImageView.center = center
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension UIImageView {
    
    private struct CJImageViewKey {
        static var cj_holderKey: Void?
    }
    
    /// 图片占位图
    var cj_imageHolderView: CJExtenImageHolder? {
        get {
            return objc_getAssociatedObject(self, &CJImageViewKey.cj_holderKey) as? CJExtenImageHolder
        }
        set {
            objc_setAssociatedObject(self, &CJImageViewKey.cj_holderKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
    
    /// 加载网络图片 设置cj_holderImage
    func cj_sd_setImage(_ urlStr: String, cj_holderImage: UIImage? = nil) {
        
        let url = urlStr.cj_urlEncodeURL
        
        if let cj_imageHolderView = self.cj_imageHolderView {
            if self.subviews.contains(cj_imageHolderView) {
                cj_imageHolderView.removeFromSuperview()
            }
        }
        
        var  cj_holderClassTemp: AnyClass? = CJExtenImageHolderView.self
        if let className = CJPack.shared.imageHolderConfig.className {
            cj_holderClassTemp = NSClassFromString(className)
        }
        
        let cj_holderClass = cj_holderClassTemp as! CJExtenImageHolder.Type
        cj_imageHolderView = cj_holderClass.init()
    
        if let cj_imageHolderView = cj_imageHolderView  {
            addSubview(cj_imageHolderView)
            cj_imageHolderView.snp.makeConstraints { make in
                make.left.right.top.bottom.equalTo(0)
            }
        }
         
        let imageName = CJPack.shared.imageHolderConfig.imageName ?? "cj_image_loadfailed"
        cj_imageHolderView?.cj_data = UIImage(named: imageName, in: .cj_bundle, compatibleWith: nil)
        
        if let cj_holderImage = cj_holderImage {
            cj_imageHolderView?.cj_data = cj_holderImage
        }
        
        sd_setImage(with: url) { [weak self] image, error, type, url in
            if image != nil, self?.cj_imageHolderView != nil {
                self?.cj_imageHolderView?.removeFromSuperview()
            }
        }
    }
    
    /// 加载网络图片 设置sd_holderImage
    func cj_sdSetImage(_ urlStr: String, sd_holderImage: UIImage? = nil,
                        cj_completed: ((UIImage?, Error?, Int, URL?) -> ())? = nil) {
        
        let url = urlStr.cj_urlEncodeURL
        sd_setImage(with: url, placeholderImage: sd_holderImage) { image, error, type, url in
            if let cj_completed = cj_completed {
                cj_completed(image, error, type.rawValue, url)
            }
        }
    }
}
